package com.recSys.controller;

import com.recSys.dataProcessing.Deal4RecGoods;
import com.recSys.inter.*;
import com.recSys.model.BusiProcBaseInfo;
import com.recSys.model.User;
import com.recSys.model.UserFeedBackInfo;
import com.recSys.util.HuiMinType;
import com.recSys.util.JsonHandler;
import com.recSys.util.LogRecord;
import com.recSys.util.OAuthHandler;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by dell on 2018/1/21.
 */
@Controller
@RequestMapping("/FBPInfo")
public class FBPInfoController {
    @Autowired
    BusiProcBaseInfoMapper bpBaseInfoMapper;
    @Autowired
    UserFeedBackInfoMapper userFeedBackInfoMapper;
    @Autowired
    RecResultMapper recResultMapper;
    @Autowired
    AreaCodeMapper areaCodeMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    EthnicMapper ethnicMapper;

    /**
     * 开启一条流程
     * @param request
     * @return
     */
    @RequestMapping(value="/createBusiProcess",method= RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createBusiProcess(HttpServletRequest request) {
        try {
            String jsonStr = JsonHandler.readJsonFromRequest(request);
            JSONObject obj = JSONObject.fromObject(jsonStr);
			Map<String,Object> isLogin = OAuthHandler.ApiValidateUserLogin(obj);
			if(isLogin.containsKey("errorcode"))
				return JsonHandler.writeJsontoResponse((int)isLogin.get("errorcode"), "");
			User user = (User) isLogin.get("user");
            BusiProcBaseInfo bpbi = new BusiProcBaseInfo();
            bpbi.setUserID(user.getId());
            String deadIDNumber = obj.getString("deadIDNumber");
            bpbi.setDeadIDNumber(deadIDNumber);
            String deadName = obj.getString("deadName");
            bpbi.setDeadName(deadName);
            int deadHMPolicyType = obj.getInt("deadHMPolicyType");
            bpbi.setDeadHMPolicyType(deadHMPolicyType);
            if(obj.containsKey("relation")) {
                String relation = obj.getString("relation");
                bpbi.setRelation(relation);
            }
            if(obj.containsKey("deadEthnic")) {
                String deadEthnic = obj.getString("deadEthnic");
                int ethnicID = ethnicMapper.selectByKeyword("%"+deadEthnic+"%").getId();
                bpbi.setDeadEthnic(ethnicID);
            }
            if(obj.containsKey("deadEducation")) {
                int deadEducation = obj.getInt("deadEducation");
                bpbi.setDeadEducation(deadEducation);
            }
            if(obj.containsKey("deadPolitical")) {
                int deadPolitical = obj.getInt("deadPolitical");
                bpbi.setDeadPolitical(deadPolitical);
            }
            if(obj.containsKey("deadReligion")) {
                int deadReligion = obj.getInt("deadReligion");
                bpbi.setDeadReligion(deadReligion);
            }
            if(obj.containsKey("deadPopulace")) {
                String deadPopulace = obj.getString("deadPopulace");
                bpbi.setDeadPopulace(deadPopulace);
            }
            bpbi.setState(0);
            bpbi.setAddTime(new Date());
            bpbi.setUpdateTime(new Date());
            bpBaseInfoMapper.insertSelective(bpbi);
            return JsonHandler.writeJsontoResponse(7000, bpbi.getID());
        } catch (JSONException e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7003, "");
        }catch (Exception e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7001, "");
        }
    }


    /**
     * 获取相似度最高的10个逝者记录ID
     *
     * @return
     */
    @RequestMapping(value="/caculateSimilarity",method= RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> caculateSimilarity(HttpServletRequest request) {
        try {
            String jsonStr = JsonHandler.readJsonFromRequest(request);
            JSONObject obj = JSONObject.fromObject(jsonStr);
            Map<String,Object> isLogin = OAuthHandler.ApiValidateUserLogin(obj);
            if(isLogin.containsKey("errorcode"))
                return JsonHandler.writeJsontoResponse((int)isLogin.get("errorcode"), "");
            int bpID = obj.getInt("bpID");
            BusiProcBaseInfo bpInfo = bpBaseInfoMapper.selectByPrimaryKey(bpID);
            int[] hmType = new HuiMinType().getHmType();
            StringBuilder sb = new StringBuilder();
            String userCardID = userMapper.selectByPrimaryKey(bpInfo.getUserID()).getIDCard();
            int c_POSID = areaCodeMapper.selectByPrimaryKey(userCardID.substring(0, 6)).getId();
            sb.append(c_POSID + ":1 ");
            int c_age = 2018 - Integer.valueOf(userCardID.substring(6, 10));
            sb.append("4729:" + c_age / 100.0 + " ");
            int c_sex = userCardID.charAt(16) - '0';
            if (c_sex % 2 == 0) sb.append("4731:1 ");
            else sb.append("4730:1 ");
            String deadCardID = bpInfo.getDeadIDNumber();
            int d_sex = userCardID.charAt(16) - '0';
            if (d_sex % 2 == 0) sb.append("4733:1 ");
            else sb.append("4732:1 ");
            int d_age = 2018 - Integer.valueOf(deadCardID.substring(6, 10));
            sb.append("4734:" + d_age / 100.0 + " ");
            int d_POSID = areaCodeMapper.selectByPrimaryKey(deadCardID.substring(0, 6)).getId();
            sb.append(4734 + Integer.valueOf(d_POSID) + ":1 ");
            sb.append(9462 + hmType[Integer.valueOf(bpInfo.getDeadHMPolicyType())] + ":1 ");
        //        sb.append(9475 + Integer.valueOf(bpInfo.getDeadEthnic()) + ":1 "); //民族String暂时未处理为代号
            if (bpInfo.getDeadReligion() != null)
                sb.append(9534 + Integer.valueOf(bpInfo.getDeadReligion()) + ":1 ");
            System.out.println("current bpinfo features: " + sb.toString());
            TreeMap<Double, String> map = Deal4RecGoods.top10Similarity(sb.toString());
            System.out.println("10 similar deadInfo IDs: " + map);
            StringBuilder result = new StringBuilder();
            for (String value : map.values()) {
                result.append(value + " ");
            }
            bpInfo.setSimilarDeadInfoIDs(result.toString());
            bpBaseInfoMapper.updateByPrimaryKeySelective(bpInfo);
            return JsonHandler.writeJsontoResponse(7000, "");
        } catch (JSONException e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7003, "");
        }catch (Exception e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7001, "");
        }
    }

    /**
     * 获取用户流程列表
     * @param request
     * @return
     */
    @RequestMapping(value="/getBusiProcessList",method= RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getBusiProcessList(HttpServletRequest request) {
        try {
            String jsonStr = JsonHandler.readJsonFromRequest(request);
            JSONObject obj = JSONObject.fromObject(jsonStr);
            Map<String,Object> isLogin = OAuthHandler.ApiValidateUserLogin(obj);
            if(isLogin.containsKey("errorcode"))
                return JsonHandler.writeJsontoResponse((int)isLogin.get("errorcode"), "");
            User user = (User) isLogin.get("user");
            List<BusiProcBaseInfo> bpbis = bpBaseInfoMapper.selectByUserID(user.getId());
            return JsonHandler.writeJsontoResponse(7000, bpbis);
        } catch (JSONException e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7003, "");
        }catch (Exception e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7001, "");
        }
    }

    /**
     * 获取某流程信息
     * @param request
     * @return
     */
    @RequestMapping(value="/getBusiProcessInfo",method= RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getBusiProcessInfo(HttpServletRequest request) {
        try {
            String jsonStr = JsonHandler.readJsonFromRequest(request);
            JSONObject obj = JSONObject.fromObject(jsonStr);
            Map<String,Object> isLogin = OAuthHandler.ApiValidateUserLogin(obj);
            if(isLogin.containsKey("errorcode"))
                return JsonHandler.writeJsontoResponse((int)isLogin.get("errorcode"), "");
            int bpID = obj.getInt("bpID");
            BusiProcBaseInfo bpbi = bpBaseInfoMapper.selectByPrimaryKey(bpID);
            return JsonHandler.writeJsontoResponse(7000, bpbi);
        } catch (JSONException e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7003, "");
        }catch (Exception e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7001, "");
        }
    }

    /**
     * 更新某流程状态
     * @param request
     * @return
     */
    @RequestMapping(value="/updateBusiProcessState",method= RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateBusiProcessState(HttpServletRequest request) {
        try {
            String jsonStr = JsonHandler.readJsonFromRequest(request);
            JSONObject obj = JSONObject.fromObject(jsonStr);
            Map<String,Object> isLogin = OAuthHandler.ApiValidateUserLogin(obj);
            if(isLogin.containsKey("errorcode"))
                return JsonHandler.writeJsontoResponse((int)isLogin.get("errorcode"), "");
            int bpID = obj.getInt("bpID");
            int state = obj.getInt("state");
            BusiProcBaseInfo bpbi = bpBaseInfoMapper.selectByPrimaryKey(bpID);
            bpbi.setState(state);
            bpbi.setUpdateTime(new Date());
            bpBaseInfoMapper.updateByPrimaryKeySelective(bpbi);
            int maxItemTypeIndex = 0;
            if(state == 3) //联系殡仪馆完成
                maxItemTypeIndex = 1;
            if(state == 4) //接送遗体完成
                maxItemTypeIndex = 2;
            if(state == 5) //火化告别开始
                maxItemTypeIndex = 2;
            if(state == 6 ) //火化告别结束
                maxItemTypeIndex = 6;
            if(state == 7) //骨灰安葬开始
                maxItemTypeIndex = 6;
            if(state == 8){ //流程结束
                maxItemTypeIndex = 8;
                //TODO 将用户数据加入训练集
            }
            if(maxItemTypeIndex != 0)
                recResultMapper.updateByItemType(bpID, maxItemTypeIndex);
            return JsonHandler.writeJsontoResponse(7000, state);
        } catch (JSONException e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7003, "");
        }catch (Exception e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7001, "");
        }
    }


    /**
     * 用户反馈
     * @param request
     * @return
     */
    @RequestMapping(value="/feedback",method= RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> feedback(HttpServletRequest request) {
        try {
            String jsonStr = JsonHandler.readJsonFromRequest(request);
            JSONObject obj = JSONObject.fromObject(jsonStr);
            Map<String,Object> isLogin = OAuthHandler.ApiValidateUserLogin(obj);
            if(isLogin.containsKey("errorcode"))
                return JsonHandler.writeJsontoResponse((int)isLogin.get("errorcode"), "");
            int bpID = obj.getInt("bpID");
            int itemType = obj.getInt("itemType");
            int itemID = obj.getInt("itemID");
            int actionType = obj.getInt("actionType");
            UserFeedBackInfo fd = new UserFeedBackInfo();
            fd.setBpID(bpID);
            fd.setItemType(itemType);
            fd.setItemID(itemID);
            fd.setActionType(actionType);
            fd.setAddTime(new Date());
            userFeedBackInfoMapper.insertSelective(fd);
            return JsonHandler.writeJsontoResponse(7000, "");
        } catch (JSONException e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7003, "");
        }catch (Exception e) {
            e.printStackTrace();
            LogRecord.ERROR.error(e.toString());
            return JsonHandler.writeJsontoResponse(7001, "");
        }
    }


}
